package com.zzl.example.springboottest.util;

import com.zzl.example.springboottest.bean.Student;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class ReflectionExample {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Alice", 22, 8000.0, 2000.0),
            new Student("Bob", 24, 7000.0, 1500.0),
            new Student("Charlie", 26, 6000.0, 1000.0)
        );

        List<Double> salaries = getFieldValues(students, "salary");

        // 输出薪水
        salaries.forEach(System.out::println);
        Double reduce = salaries.stream().reduce(0.0, Double::sum);
        System.out.println(reduce);
    }
 
    public static <T> List<Double> getFieldValues(List<T> objects, String fieldName) {
        return objects.stream()
            .map(obj -> {
                try {
                    Field field = obj.getClass().getDeclaredField(fieldName);
                    field.setAccessible(true);
                    return (Double) field.get(obj);
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            })
            .collect(Collectors.toList());
    }
}